package com.wlient.basic.Thread.newThread;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

/**
 * @author: 史炜立
 * @description: TODO
 * @date: 2021/12/13 11:04
 */
public class CallableDemo2{
    private  List<Integer> list = Arrays.asList(1,11,3,7,9,27,11,18,26);

    private Integer getMin(List<Integer> list) throws InterruptedException {
        Integer min = list.stream().min(Integer::compareTo).get();
        Thread.sleep(300);
        return min;
    }

    private Integer getMax(List<Integer> list) throws InterruptedException {
        Integer max = list.stream().max(Integer::compareTo).get();
        Thread.sleep(300);
        return max;
    }

    private BigDecimal getAvg(List<Integer> list) throws InterruptedException {
        BigDecimal avg = BigDecimal.valueOf(list.stream().mapToDouble(Integer::doubleValue).average().getAsDouble()).setScale(4, BigDecimal.ROUND_HALF_UP);
        Thread.sleep(300);
        return avg;
    }

    private Map<String,Object> test() throws ExecutionException, InterruptedException {
        Map<String,Object> map = new HashMap<>();
        FutureTask<Integer> maxTask = new FutureTask<>(() -> this.getMax(this.list));
        new Thread(maxTask, "getMax").start();

        FutureTask<Integer> minTask = new FutureTask<>(() -> this.getMin(this.list));
        new Thread(minTask, "getMin").start();

        FutureTask<BigDecimal> avgTask = new FutureTask<>(() -> this.getAvg(this.list));
        new Thread(avgTask, "getAvg").start();


        //获取结果的时候会阻塞线程
        Integer max = maxTask.get();
        Integer min = minTask.get();
        BigDecimal avg = avgTask.get();
        map.put("max",max);
        map.put("min",min);
        map.put("avg",avg);
        map.put("range",max - min);
        System.out.println(map);
        return map;
    }
    private Map<String,Object> test2() throws InterruptedException {
        Map<String,Object> map = new HashMap<>();
        Integer max = this.getMax(this.list);
        Integer min = this.getMin(this.list);
        BigDecimal avg =this.getAvg(this.list);
        map.put("max",max);
        map.put("min",min);
        map.put("avg",avg);
        map.put("range",max - min);
        System.out.println(map);
        return map;
    }
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        long startTime = System.currentTimeMillis();
        CallableDemo2 callableDemo2 = new CallableDemo2();
        callableDemo2.test();
//        callableDemo2.test2();
        System.out.println(System.currentTimeMillis()-startTime);

    }

}
